import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:wms/utils/utils.dart';
import '/models/LoadTaskData.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import '../../services/api_service.dart';
import 'package:provider/provider.dart';
import '../../services/auth_service.dart';
import '../system/fontsize_provider.dart';
import '../../utils/message_box.dart';
import '../../models/cycle_count_response.dart';

class SearchDetaiScreen extends StatefulWidget {
  const SearchDetaiScreen({super.key});

  @override
  _SearchDetaiScreenState createState() => _SearchDetaiScreenState();
}

class _SearchDetaiScreenState extends State<SearchDetaiScreen> with WidgetsBindingObserver {
  late LoadTaskData taskData;
  Map<String, dynamic>? selectedSkuItem; // 存储选中的SKU对象
  final TextEditingController locationController = TextEditingController();
  final TextEditingController skuController = TextEditingController();
  final TextEditingController quantityController = TextEditingController();
  
  // FocusNodes（增强：支持禁用默认键盘触发）
  final FocusNode _locationFocusNode = FocusNode(canRequestFocus: true);
  final FocusNode _skuFocusNode = FocusNode(canRequestFocus: true);
  
  // 键盘状态管理（默认全部收起）
  bool _locationKeyboardVisible = false;
  bool _skuKeyboardVisible = false;
  String? _currentFocusField;

  String? sku;
  String? oldsku;
  String? lpnNumber;
  String? shipmentCode;
  String? packKey;
  
  int? warehouseId;
  int? locationId; // 选中的SKU的id
  int? quantity = 0;
  String? location;
  // 存储SKU详情对象的列表
  List<Map<String, dynamic>> availableSkus = []; 
  double baseFontSize = 13;
  double listFontSize = 12;
  late double _fontScale;
  int? maxAllowedValue = 9999999;

  bool showClean = false;

  // 分页控制
  late ScrollController scrollController; // 滚动控制器
  int currentPage = 1; // 当前页码，初始为1
  bool isLoading = false; // 是否正在加载
  bool hasMore = true; // 是否有更多数据
  final int pageSize = 20; // 每页加载20条

  // 关键：底部按钮区域总高度 + 列表上下边距
  static const double _buttonAreaHeight = 60;
  static const double _inputAreaMargin = 40; // 输入框+标题的固定高度（上下间距+内容高度）

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this); // 应用生命周期监听
    
    // 初始化焦点监听（增强：防止聚焦自动弹键盘）
    _initFocusListeners();
    
    // 关键修改1：初始聚焦Location，先隐藏键盘再聚焦
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      if (mounted) {
        await _hideKeyboard();
        _focusOnField('location', showKeyboard: false);
      }
    });
    
    // 添加SKU输入框焦点监听器（保留原逻辑并增强）
    _skuFocusNode.addListener(() {
      if (_skuFocusNode.hasFocus && skuController.text.isNotEmpty) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          skuController.selection = TextSelection(
            baseOffset: 0,
            extentOffset: skuController.text.length,
          );
        });
      }
      // 增强：焦点变化时强制隐藏未触发的键盘
      if (_skuFocusNode.hasFocus && !_skuKeyboardVisible) {
        _hideKeyboard();
      }
    });

    // 添加文本变化监听器，用于更新清除按钮显示状态
    locationController.addListener(() {
      setState(() {});
    });
    skuController.addListener(() {
      setState(() {});
    });

    // 初始化滚动控制器并添加监听（列表单独滚动）
    scrollController = ScrollController();
    scrollController.addListener(_onScroll);
  }

  // 初始化焦点监听（增强：焦点变化时强制隐藏键盘）
  void _initFocusListeners() {
    _locationFocusNode.addListener(() {
      _handleFocusChange('location', _locationFocusNode);
      if (_locationFocusNode.hasFocus && !_locationKeyboardVisible) {
        _hideKeyboard();
      }
    });
    _skuFocusNode.addListener(() {
      _handleFocusChange('sku', _skuFocusNode);
      if (_skuFocusNode.hasFocus && !_skuKeyboardVisible) {
        _hideKeyboard();
      }
    });
  }

  // 应用生命周期监听（恢复时重置键盘）
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed && mounted) {
      _resetAllKeyboards();
    }
  }

  // 关键修改2：移除焦点变化时的自动弹键盘逻辑，仅跟踪焦点状态
  void _handleFocusChange(String field, FocusNode node) {
    if (node.hasFocus) {
      // 切换焦点时先隐藏其他键盘
      if (_currentFocusField != null && _currentFocusField != field) {
        _hideKeyboardForField(_currentFocusField!);
      }
      _setCurrentFocusField(field);
    } else if (_currentFocusField == field) {
      // 失去焦点时隐藏当前键盘
      _hideKeyboardForField(field);
      _currentFocusField = null;
    }
  }

  // 键盘控制方法
  void _setCurrentFocusField(String field) => setState(() => _currentFocusField = field);
  
  void _showKeyboard() async => await SystemChannels.textInput.invokeMethod('TextInput.show');
  
  // 关键修改3：增强键盘隐藏方法（增加延迟重试）
  Future<void> _hideKeyboard() async {
    try {
      await SystemChannels.textInput.invokeMethod('TextInput.hide');
      await Future.delayed(const Duration(milliseconds: 50));
      await SystemChannels.textInput.invokeMethod('TextInput.hide');
    } catch (e) {
      print('隐藏键盘失败: $e');
      await Future.delayed(const Duration(milliseconds: 100));
      await SystemChannels.textInput.invokeMethod('TextInput.hide');
    }
  }
  
  // 显示键盘（仅手动触发时调用）
  void _showKeyboardForField(String field) => setState(() {
    _updateKeyboardState(field, true);
    _showKeyboard();
  });
  
  // 隐藏键盘（同步状态）
  void _hideKeyboardForField(String field) => setState(() {
    _updateKeyboardState(field, false);
    _hideKeyboard();
  });
  
  // 切换键盘状态（键盘图标点击触发）
  void _toggleKeyboardForField(String field) {
    if (_getKeyboardState(field)) {
      _hideKeyboardForField(field);
      _unfocusField(field);
    } else {
      _focusOnField(field, showKeyboard: true);
    }
  }
  
  // 关键修改4：优化聚焦方法（增加状态同步，确保图标正确）
  void _focusOnField(String field, {required bool showKeyboard}) {
    FocusScope.of(context).unfocus();
    if (mounted) {
      switch (field) {
        case 'location':
          FocusScope.of(context).requestFocus(_locationFocusNode);
          break;
        case 'sku':
          FocusScope.of(context).requestFocus(_skuFocusNode);
          break;
      }
      // 关键：无论是否显示键盘，都明确更新状态变量
      if (showKeyboard) {
        _showKeyboardForField(field);
      } else {
        _hideKeyboard();
        _updateKeyboardState(field, false); // 确保聚焦但不显示键盘时，状态同步
      }
    }
  }
  
  // 取消指定输入框焦点
  void _unfocusField(String field) {
    switch (field) {
      case 'location': _locationFocusNode.unfocus(); break;
      case 'sku': _skuFocusNode.unfocus(); break;
    }
  }
  
  // 获取键盘状态
  bool _getKeyboardState(String field) {
    switch (field) {
      case 'location': return _locationKeyboardVisible;
      case 'sku': return _skuKeyboardVisible;
      default: return false;
    }
  }
  
  // 更新键盘状态
  void _updateKeyboardState(String field, bool visible) {
    setState(() {
      switch (field) {
        case 'location': _locationKeyboardVisible = visible; break;
        case 'sku': _skuKeyboardVisible = visible; break;
      }
    });
  }
  
  // 重置所有键盘状态（点击空白区域调用）
  void _resetAllKeyboards() {
    if (_currentFocusField == null && !_locationKeyboardVisible && !_skuKeyboardVisible) {
      return;
    }
    setState(() {
      _locationKeyboardVisible = false;
      _skuKeyboardVisible = false;
      _currentFocusField = null;
    });
    FocusScope.of(context).unfocus();
    _hideKeyboard();
  }

  // 关键修改5：输入框点击处理（仅聚焦不自动弹键盘，确保图标初始为"收起"）
  void _onInputTap(TextEditingController controller, String fieldType) {
    // 选中全部文本
    if (controller.text.isNotEmpty) {
      controller.selection = TextSelection(
        baseOffset: 0,
        extentOffset: controller.text.length,
      );
    }
    // 聚焦但不自动弹键盘（核心修复：点击输入框时图标保持"收起"状态）
    _focusOnField(fieldType, showKeyboard: false);
  }

  // 滚动监听：当接近底部时加载更多（保留原逻辑，列表单独触发）
  void _onScroll() {
    if (!isLoading && hasMore && 
        scrollController.position.pixels >= 
        scrollController.position.maxScrollExtent - 100) { // 距离底部100px时加载
      _loadMoreData();
    }
  }

  // 清除输入框内容（优化焦点处理，不弹键盘）
  void _clearTextField(TextEditingController controller) {
    controller.clear();
    setState(() {
      showClean = false;
    });
    // 清除后重新聚焦，不弹键盘
    if (controller == locationController) {
      _focusOnField('location', showKeyboard: false);
      _handleLocationInput('');
    } else if (controller == skuController) {
      _focusOnField('sku', showKeyboard: false);
      _handleItemInput('');
    }
  }

  // 选择SKU处理（保留原逻辑）
  void _handleSkuSelection(Map<String, dynamic> skuItem) {
    setState(() {
      if (selectedSkuItem == skuItem) {
        selectedSkuItem = null;
      } else {
        selectedSkuItem = skuItem;
      }
    });
  }

  // 处理SKU输入（优化焦点逻辑，不弹键盘）
  _handleItemInput(String value) async {
    try {
      String parsedValue = value;
      if(parsedValue.contains(':')){
        parsedValue = Utils.parseQRCode(parsedValue, 'item number');
      }
      
      setState(() {
        skuController.text = parsedValue;
        if (skuController.text.isNotEmpty) {
          skuController.selection = TextSelection(
            baseOffset: 0,
            extentOffset: skuController.text.length,
          );
        }
        currentPage = 1;
        hasMore = true;
      });

      if (mounted) {
        setState(() {
          availableSkus = [];
          selectedSkuItem = null;
        });
      }
      
      // 调用接口并处理返回数据
      final cycleResponse = await _fetchSKUsByLocation(
        warehouseId, 
        locationController.text, 
        parsedValue.trim(),
        currentPage,
        pageSize,
        );
      if (cycleResponse != null && cycleResponse.code == 2000) {
        List<Map<String, dynamic>> newSkuList = [];
        if (cycleResponse.data != null && cycleResponse.data!.isNotEmpty) {
          for (var detail in cycleResponse.data!) {
            newSkuList.add({
              'id': detail.id,
              'itemNumber': detail.itemNumber ?? 'N/A',
              'packType': detail.packType ,
              'packKey': detail.packKey ,
              'packTypeQuantity': detail.packTypeQuantity,
              'quantity': detail.quantity ?? 0,
              'location': detail.location.number,
            });
          }
        }
        setState(() {
          availableSkus = newSkuList;
          hasMore = newSkuList.length == pageSize;
        });
      } else {
        if(cycleResponse != null){
          MessageBox.showMessageBox(context, cycleResponse.msg, isError: true);
        }
      }
    } catch (e) {
      setState(() {
        skuController.text = value;
        skuController.selection = TextSelection(
          baseOffset: 0,
          extentOffset: value.length,
        );
      });
      MessageBox.showMessageBox(context, e.toString(), isError: true);
    }
  }

  // 处理库位输入（优化焦点逻辑，不弹键盘）
  _handleLocationInput(String value) async{
    String parsedValue = value.trim();
    try {
      if(parsedValue.contains(':')){
        parsedValue = Utils.parseQRCode(parsedValue, 'location');
      }
    } catch (e) {
      print("JSON解析失败: $e");
    }
    
    if (mounted) {
      setState(() {
        availableSkus = [];
        selectedSkuItem = null;
        locationController.text = parsedValue;
        location = parsedValue;
        locationController.selection = TextSelection(
          baseOffset: 0,
          extentOffset: parsedValue.length,
        );
        currentPage = 1;
        hasMore = true;
      });
    }
    // 跳转焦点到SKU，不弹键盘
    _focusOnField('sku', showKeyboard: false);
    
    // 调用接口并处理返回数据
    final cycleResponse = await _fetchSKUsByLocation(
      warehouseId, 
      parsedValue, 
      skuController.text.trim(),
      currentPage,
      pageSize,
      );
    if (cycleResponse != null && cycleResponse.code == 2000) {
      List<Map<String, dynamic>> newSkuList = [];
      if (cycleResponse.data != null && cycleResponse.data!.isNotEmpty) {
        for (var detail in cycleResponse.data!) {
          newSkuList.add({
            'id': detail.id,
            'itemNumber': detail.itemNumber ?? 'N/A',
            'packType': detail.packType ,
            'packKey': detail.packKey ,
            'packTypeQuantity': detail.packTypeQuantity,
            'quantity': detail.quantity ?? 0,
            'location': detail.location.number,
          });
        }
      }
      setState(() {
        availableSkus = newSkuList;
        hasMore = newSkuList.length == pageSize;
      });
    } else {
      if(cycleResponse != null){
        MessageBox.showMessageBox(context, cycleResponse.msg, isError: true);
      }
    }
  }

  // 调用接口获取SKU列表（保留原逻辑）
  Future<CycleCountResponse?> _fetchSKUsByLocation(
    int? warehouseId, 
    String location, 
    String itemNumber,
    int page, 
    int limit, 
    ) async {
      if(location.isEmpty && itemNumber.isEmpty){
        return null;
      }
    if (warehouseId == null) {
      throw Exception('Warehouse ID is missing');
    }

    final String locationParam = location.isNotEmpty ? '&location=$location' : '';
    final String itemNumberParam = itemNumber.isNotEmpty ? '&item_number=$itemNumber' : '';
    final String pageParam = '&page=$page';
    final String limitParam = '&limit=$limit';
    final apiUrl = '${ApiService.baseURL}${ApiService.fetchSKUsByLocation}warehouse=$warehouseId$locationParam$itemNumberParam$pageParam$limitParam';
    
    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;
    
    try {
      print('url--$apiUrl');
      final response = await http.get(
        Uri.parse(apiUrl),
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': '$warehouseId',
          'x-timezone': 'America/Los_Angeles',
          'Content-Type':'application/json',
          'X-Client-Type':'app'
        },
      );
      
      if (response.statusCode == 200) {
        String responseBody = utf8.decode(response.bodyBytes);
        Map<String, dynamic> jsonData = json.decode(responseBody);
        return CycleCountResponse.fromJson(jsonData);
      } else if (response.statusCode == 401) {
        AuthService auth = AuthService();
        auth.logout(context);
        throw Exception('The session has expired, Please log in again.');
      } else {
        throw Exception('Server error: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('$e');
    }
  }

  // 加载更多数据（保留原逻辑）
  Future<void> _loadMoreData() async {
    if (isLoading || !hasMore) return;

    setState(() {
      isLoading = true;
    });

    try {
      final cycleResponse = await _fetchSKUsByLocation(
        warehouseId,
        locationController.text,
        skuController.text.trim(),
        currentPage + 1,
        pageSize,
      );

      if (cycleResponse != null && cycleResponse.code == 2000) {
        List<Map<String, dynamic>> newSkuList = [];
        if (cycleResponse.data != null && cycleResponse.data!.isNotEmpty) {
          for (var detail in cycleResponse.data!) {
            newSkuList.add({
              'id': detail.id,
              'itemNumber': detail.itemNumber ?? 'N/A',
              'packType': detail.packType,
              'packKey': detail.packKey,
              'packTypeQuantity': detail.packTypeQuantity,
              'quantity': detail.quantity ?? 0,
              'location': detail.location.number,
            });
          }
        }

        setState(() {
          currentPage++;
          availableSkus.addAll(newSkuList);
          hasMore = newSkuList.length == pageSize;
        });
      } else {
        MessageBox.showMessageBox(context, cycleResponse!.msg, isError: true);
      }
    } catch (e) {
      MessageBox.showMessageBox(context, e.toString(), isError: true);
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  // 搜索按钮点击事件（优化键盘处理）
  void _submit() async{
    try{
      _resetAllKeyboards(); // 提交前收起所有键盘
      
      if (mounted) {
        setState(() {
          availableSkus = [];
          selectedSkuItem = null;
          currentPage = 1;
          hasMore = true;
        });
      }
      
      final cycleResponse = await _fetchSKUsByLocation(
        warehouseId, 
        locationController.text, 
        skuController.text,
        currentPage,
        pageSize,
        );
      if (cycleResponse != null && cycleResponse.code == 2000) {
        List<Map<String, dynamic>> newSkuList = [];
        if (cycleResponse.data != null && cycleResponse.data!.isNotEmpty) {
          for (var detail in cycleResponse.data!) {
            newSkuList.add({
              'id': detail.id,
              'itemNumber': detail.itemNumber ?? 'N/A',
              'packType': detail.packType ,
              'packKey': detail.packKey ,
              'packTypeQuantity': detail.packTypeQuantity,
              'quantity': detail.quantity ?? 0,
              'location': detail.location.number,
            });
          }
        }
        setState(() {
          availableSkus = newSkuList;
          hasMore = newSkuList.length == pageSize;
        });
      }
    }catch(e){
      MessageBox.showMessageBox(context, e.toString(), isError: true);
    }
  }

  // 关键修改6：优化图标Row布局，强制移动端紧凑排列
  Widget _buildInputSuffix({
    required TextEditingController controller,
    required String fieldType,
    required bool isSmallScreen,
  }) {
    // 图标尺寸：移动端更小（16px），Windows端保持原尺寸，避免占用过多空间
    final iconSize = isSmallScreen ? 16 * _fontScale : (isSmallScreen ? 18 : 20) * _fontScale;
    
    return Row(
      mainAxisSize: MainAxisSize.min, // 仅占内容宽度，避免拉伸
      mainAxisAlignment: MainAxisAlignment.center, // 图标居中对齐
      crossAxisAlignment: CrossAxisAlignment.center, // 垂直居中
      spacing: 2, // 图标之间固定小间距（2px），移动端强制紧凑
      children: [
        // 清除按钮（原有功能，优化内边距和约束）
        if (controller.text.isNotEmpty)
          // IconButton(
          //   icon: Icon(Icons.clear, size: iconSize, color: Colors.red),
          //   onPressed: () => _clearTextField(controller),
          //   padding: EdgeInsets.symmetric(horizontal: 2, vertical: 2), // 最小内边距
          //   constraints: BoxConstraints.tightFor(width: 24, height: 24), // 固定24x24大小
          //   splashRadius: 10, // 缩小点击反馈范围，避免影响布局
          //   visualDensity: VisualDensity.compact, // 紧凑视觉密度，减少额外空间
          // ),
        // 键盘图标（优化尺寸和间距）
        IconButton(
          icon: Icon(
            _getKeyboardState(fieldType) ? Icons.keyboard_hide : Icons.keyboard,
            color: const Color(0xFF008363),
            size: iconSize,
          ),
          onPressed: () => _toggleKeyboardForField(fieldType),
          padding: EdgeInsets.symmetric(horizontal: 2, vertical: 2), // 最小内边距
          constraints: BoxConstraints.tightFor(width: 24, height: 24), // 固定24x24大小
          splashRadius: 10, // 统一点击反馈范围
          visualDensity: VisualDensity.compact, // 紧凑视觉密度
        ),
      ],
    );
  }

  // 关键修改7：优化输入框suffixIcon约束，防止移动端拉伸
  Widget _buildLocationInput(bool isSmallScreen) {
    return Row(
      children: [
        SizedBox(
          width: isSmallScreen ? 80 : 100,
          child: Text(
            'Location:',
            style: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: baseFontSize * _fontScale
            ),
          ),
        ),
        const SizedBox(width: 10),
        Expanded(
          child:SizedBox(
            height: 30,
            child: TextField(
              controller: locationController,
              focusNode: _locationFocusNode,
              decoration: InputDecoration(
                border: const OutlineInputBorder(),
                contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
                // 关键：限制suffixIcon宽度，强制图标紧凑排列（两个24px图标+4px间距=52px）
                suffixIconConstraints: BoxConstraints.tightFor(width: 40, height: 30),
                // 替换原有suffixIcon为"清除+键盘"组合
                suffixIcon: _buildInputSuffix(
                  controller: locationController,
                  fieldType: 'location',
                  isSmallScreen: isSmallScreen,
                ),
              ),
              onChanged: (value) {
                setState(() => showClean = value.isNotEmpty);
              },
              style: TextStyle(fontSize: baseFontSize * _fontScale),
              textInputAction: TextInputAction.next,
              onSubmitted: _handleLocationInput,
              // 输入框点击：仅聚焦不弹键盘（核心修复）
              onTap: () => _onInputTap(locationController, 'location'),
              // 输入框外部点击：确保状态同步
              onTapOutside: (event) {
                _hideKeyboardForField('location');
                _unfocusField('location');
              },
            ),
          ),
        ),
      ],
    );
  }

  // 关键修改8：SKU输入框同步优化suffixIcon约束
  Widget _buildSkuInputSection(bool isSmallScreen) {
    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.only(bottom: 16),
          child: Row(
            children: [
              SizedBox(
                width: isSmallScreen ? 80 : 100,
                child: Text(
                  'Item Number:',
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: baseFontSize * _fontScale
                  ),
                ),
              ),
              const SizedBox(width: 10),
              Expanded(
                child:SizedBox(
                  height: 30,
                  child: TextField(
                    controller: skuController,
                    focusNode: _skuFocusNode,
                    decoration: InputDecoration(
                      border: const OutlineInputBorder(),
                      contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
                      // 关键：统一suffixIcon宽度约束，确保与Location输入框一致
                      suffixIconConstraints: BoxConstraints.tightFor(width: 40, height: 30),
                      // 替换原有suffixIcon为"清除+键盘"组合
                      suffixIcon: _buildInputSuffix(
                        controller: skuController,
                        fieldType: 'sku',
                        isSmallScreen: isSmallScreen,
                      ),
                    ),
                    style: TextStyle(fontSize: baseFontSize * _fontScale),
                    onChanged: (value) {
                      setState(() => showClean = value.isNotEmpty);
                    },
                    // 输入框点击：仅聚焦不弹键盘（核心修复）
                    onTap: () => _onInputTap(skuController, 'sku'),
                    // 输入框外部点击：确保状态同步
                    onTapOutside: (event) {
                      _hideKeyboardForField('sku');
                      _unfocusField('sku');
                    },
                    onSubmitted: _handleItemInput,
                  ),
                )
              ),
            ],
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    _fontScale = Provider.of<FontSizeProvider>(context).fontScale;
    final user = Provider.of<AuthService>(context).currentUser;
    warehouseId = user?.warehouse;
    final mediaQuery = MediaQuery.of(context);
    final isSmallScreen = mediaQuery.size.width < 360;
    // 关键修改6：计算列表可用高度（屏幕高度 - 导航栏 - 输入区 - 底部按钮 - 内边距）
    final appBarHeight = AppBar().preferredSize.height; // 导航栏高度
    final screenHeight = mediaQuery.size.height; // 屏幕总高度
    // 列表可用高度 = 屏幕高度 - 导航栏 - 底部按钮 - 输入区固定高度 - 页面上下内边距
    final listAvailableHeight = screenHeight - appBarHeight - _buttonAreaHeight - _inputAreaMargin - 32; // 32是页面上下16px内边距总和

    return Scaffold(
      appBar: AppBar(
        title: Text('Search', style: TextStyle(fontSize: 18 * _fontScale)),
        automaticallyImplyLeading: false,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () {
            _resetAllKeyboards(); // 返回前收起键盘
            Navigator.pop(context);
          },
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.home, color: Colors.white),
            onPressed: () {
              _resetAllKeyboards(); // 跳转首页前收起键盘
              Navigator.pushNamed(context, '/home');
            },
          ),
        ],
        backgroundColor: const Color(0xFF008363),
      ),
      // 关键修改7：禁止页面随键盘调整，避免间接触发整体滚动
      resizeToAvoidBottomInset: false,
      body: GestureDetector(
        onTap: _resetAllKeyboards, // 点击空白区域重置键盘
        behavior: HitTestBehavior.translucent,
        child: Padding(
          padding: EdgeInsets.all(isSmallScreen ? 16 : 32),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              // 1. 输入框区域（固定高度，不随列表滚动）
              _buildLocationInput(isSmallScreen),
              const SizedBox(height: 20),
              _buildSkuInputSection(isSmallScreen),
              const SizedBox(height: 10),
              
              // 2. 列表标题（固定位置，不随列表滚动）
              Text(
                'Products:',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: baseFontSize * _fontScale
                ),
              ),
              const SizedBox(height: 8),
              
              // 关键修改8：列表区域（固定高度，单独滚动）
              Expanded(
                child: Container(
                  // 限制列表最大高度为计算出的可用高度，最小高度200px
                  constraints: BoxConstraints(
                    minHeight: 200,
                    maxHeight: listAvailableHeight > 200 ? listAvailableHeight : 200,
                  ),
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.grey, width: 1.0),
                    borderRadius: BorderRadius.circular(4.0),
                  ),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(4.0),
                    child: ListView.builder(
                      controller: scrollController,
                      // 关键：列表单独滚动，不影响页面其他部分
                      physics: const AlwaysScrollableScrollPhysics(),
                      shrinkWrap: false, // 禁用高度自适应，使用固定高度
                      itemCount: availableSkus.length + (isLoading ? 1 : 0),
                      itemBuilder: (context, index) {
                        if(index < availableSkus.length){
                          final skuItem = availableSkus[index];
                          final isSelected = selectedSkuItem == skuItem;
                          
                          return InkWell(
                            onTap: () => _handleSkuSelection(skuItem),
                            child: Container(
                              margin: const EdgeInsets.symmetric(vertical: 2),
                              decoration: BoxDecoration(
                                border: Border.all(color: const Color.fromARGB(255, 169, 168, 168), width: 0.5),
                                borderRadius: BorderRadius.circular(4.0),
                                color: isSelected ? Colors.green[50] : null,
                              ),
                              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    skuItem['itemNumber'] ?? 'N/A',
                                    style: TextStyle(
                                      fontSize: listFontSize * _fontScale,
                                      fontWeight: FontWeight.bold,
                                      color: isSelected ? Colors.green : Colors.black,
                                    ),
                                  ),
                                  const SizedBox(height: 5),
                                  Row(
                                    children: [
                                      Expanded(
                                        flex: 2,
                                        child: Row(
                                          mainAxisSize: MainAxisSize.min,
                                          children: [
                                            Text(
                                              'Location: ',
                                              style: TextStyle(
                                                fontSize: listFontSize * _fontScale,
                                                color: isSelected ? Colors.green : Colors.black87,
                                              ),
                                            ),
                                            Text(
                                              '${skuItem['location'] ?? 'N/A'}',
                                              style: TextStyle(
                                                fontSize: listFontSize * _fontScale,
                                                color: isSelected ? Colors.green : Colors.black87,
                                                fontWeight: FontWeight.bold,
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                      Expanded(
                                        flex: 2,
                                        child: Row(
                                          mainAxisSize: MainAxisSize.min,
                                          children: [
                                            Text(
                                              'PackType: ',
                                              style: TextStyle(
                                                fontSize: listFontSize * _fontScale,
                                                color: isSelected ? Colors.green : Colors.black87,
                                              ),
                                            ),
                                            Text(
                                              '${skuItem['packType'] ?? 'N/A'}',
                                              style: TextStyle(
                                                fontSize: listFontSize * _fontScale,
                                                color: isSelected ? Colors.green : Colors.black87,
                                                fontWeight: FontWeight.bold,
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                      Expanded(
                                        flex: 2,
                                        child: Row(
                                          mainAxisSize: MainAxisSize.min,
                                          children: [
                                            Text(
                                              'PackQty: ',
                                              style: TextStyle(
                                                fontSize: listFontSize * _fontScale,
                                                color: isSelected ? Colors.green : Colors.black87,
                                              ),
                                            ),
                                            Text(
                                              '${skuItem['packTypeQuantity'] ?? 0}',
                                              style: TextStyle(
                                                fontSize: listFontSize * _fontScale,
                                                color: isSelected ? Colors.green : Colors.black87,
                                                fontWeight: FontWeight.bold,
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                      Expanded(
                                        child: Row(
                                          mainAxisSize: MainAxisSize.min,
                                          children: [
                                            Text(
                                              'Qty: ',
                                              style: TextStyle(
                                                fontSize: listFontSize * _fontScale,
                                                color: isSelected ? Colors.green : Colors.black87,
                                              ),
                                            ),
                                            Text(
                                              '${skuItem['quantity'] ?? 0}',
                                              style: TextStyle(
                                                fontSize: listFontSize * _fontScale,
                                                color: isSelected ? Colors.green : Colors.black87,
                                                fontWeight: FontWeight.bold,
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          );
                        }
                        else{
                          // 加载中项
                          return const Center(
                            child: Padding(
                              padding: EdgeInsets.symmetric(vertical: 16),
                              child: CircularProgressIndicator(),
                            ),
                          );
                        }
                      },
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
      // 关键修改9：底部按钮用BottomAppBar，固定在底部，不随页面滚动
      bottomNavigationBar: BottomAppBar(
        color: Theme.of(context).scaffoldBackgroundColor,
        elevation: 0,
        child: Container(
          padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 32),
          height: _buttonAreaHeight, // 固定按钮区域高度
          child: Center(
            child: SizedBox(
              width: 240,
              height: 40,
              child: ElevatedButton(
                onPressed: _submit,
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFF008363),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8.0),
                  ),
                ),
                child: Text(
                  'Search',
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: baseFontSize * _fontScale,
                    color: Colors.white
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this); // 移除生命周期监听
    
    // 移除焦点监听
    _locationFocusNode.removeListener(() => _handleFocusChange('location', _locationFocusNode));
    _skuFocusNode.removeListener(() => _handleFocusChange('sku', _skuFocusNode));
    
    // 保留原销毁逻辑
    scrollController.dispose();
    _locationFocusNode.dispose();
    _skuFocusNode.dispose();
    locationController.dispose();
    skuController.dispose();
    quantityController.dispose();
    
    super.dispose();
  }
}